import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, type MessageHandler } from 'element-plus';
import { toURLSearch } from '@/utils/common';

// 提示拦截

let messageInstance: MessageHandler;
const message_error = (info: string) => {
    if (messageInstance) {
        messageInstance.close();
    }
    messageInstance = ElMessage.error({
        type: 'error',
        message: info,
        duration: 30000,
        showClose: true,
    });
};

const service = axios.create({
    // baseURL: import.meta.env.VITE_APP_BASE_API_URL,
    baseURL: 'http://localhost:3000',
    timeout: 60000,
    headers: { 'Content-Type': 'application/json;charset=utf-8', 'X-Requested-With': 'XMLHttpRequest' },
});
/** @ts-ignore  */
// 请求拦截器
service.interceptors.request.use(
    async (config: InternalAxiosRequestConfig) => {
        requestInterceptor(config);
        return config;
    },
    (error) => {
        console.error(error);
        return Promise.reject(new Error('网络错误'));
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        const { code, msg, message, data } = response.data;
        if (code == 0) {
            return response.data;
        } else {
            message_error(msg || message || '系统出错');
            return Promise.reject('Error');
        }
    },
    (error: any) => {
        if (error.response && error.response.data) {
            const { msg, message } = error.response.data;
            message_error(msg || message || '系统出错');
        } else if (error.message == 'canceled') {
            console.log('请求已取消');
        } else {
            message_error(error.message);
        }

        return Promise.reject(error.message);
    }
);

/**
 * 请求拦截处理
 */
export function requestInterceptor(config: any) {
    // 添加token到header
    const token = localStorage.getItem('token') || '735fIAr6HKgmuOKqClUaaM5LMmD8JTO3';
    if (token && config.headers) {
        config.headers['authorization'] = token;
    }
    //console.log('---->>>> ' + config.method + ':' + config.url + JSON.stringify(config.data || ''));

    // get请求处理数组和对象类型参数
    if (config.method === 'get' && config.params) {
        config.url = toURLSearch(config.params, config.url);
        config.params = {};
    }
}

// 导出 axios 实例
export default service;
